/* eslint-disable no-shadow */
import { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { View, Input, ScrollView } from '@tarojs/components'
import { AtButton } from 'taro-ui'
import { Fragment } from 'react'
import StoreListView from '@/components/StoreListView'
import classnames from 'classnames'
import { debounce } from '@/utils'
import OpenLocation from '@/components/OpenLocation'
import map from '@/utils/map'
import alipayMap from '@/utils/alipayMap'
import { hasPrevRoute } from '@/utils/global'
import { connect } from 'react-redux'
import { updateStore, initLocation } from '@/store/location/action'
import { oftenStore, nearStore as nearStoreApi, allStore } from '@/api'
import './index.scss'

interface State {
  address: any
  tabIndex: number
  store: IStore | null
  loadLocation: boolean
  otfenStore: IStore[] | null
  commonlyUsed: []
  nearStore: IStore[] | null
  reload: boolean
  keyWordStore: IStore[]
  allStoreList: IStore[]
}

@connect<any>(({ location, user }) => ({ location, user }), _dispatch => ({
  dispatchStore(params) {
    return _dispatch(updateStore(params))
  },
  dispatchLocation(params) {
    return _dispatch(initLocation(params))
  }
}))
export default class Index extends Component<any> {
  $instance = getCurrentInstance();
  constructor (props) {
    super(props)
    this.state = {
      address: null,
      tabIndex: 2,
      store: null,
      loadLocation: false,
      otfenStore: null,
      commonlyUsed: [],// 常用门店
      nearStore: null,// 附近门店
      reload: false,
      keyWordStore: [],
      allStoreList: []
    }
  }
  state: State

  UNSAFE_componentWillMount() { }
  async componentDidMount() {
    await this.currStore()
    const { address } = this.props.location
    const { tabIndex } = this.$instance.router.params
    console.log('进来--address', address)
    let params = {}
    if (address) {
      // const { lat: latitude, lng: longitude } = address.location
      const { lat, lng, latitude, longitude } = address.location
      params = {
        location: {
          latitude: lat || latitude,
          longitude: lng || longitude
        }
      }
      console.log('params--params', params)
    }
    await this.getLocation(params)
    this.getNearStore('tab')
  }
  UNSAFE_componentWillReceiveProps(nextProps, nextContext) {
    const { address } = this.state
    const { user } = this.props
    const propsLocation = nextProps.location.address
    if (propsLocation) {
      if (address) {
        if (propsLocation.address !== address.address) {
          this.setState({
            location: propsLocation,
            address: propsLocation
          }, () => {
            if (user.userInfo.accessId) {
              this.getOtfenStore(nextProps.location)
            }
          })
        }
      } else {
        const { method } = this.$instance.router.params
        if (method) {
          if (method === 'vendorStore') {
            this.getAllStore(nextProps.location)
            Taro.setNavigationBarTitle({
              title: '门店'
            })
          }
          return
        } else {
          this.setState({
            location: propsLocation,
            address: propsLocation
          }, () => {
            this.getNearStore('tab')
          })
        }
      }
    }
  }
  componentWillUnmount() { }
  componentDidShow() {
    let page = Taro.getCurrentPages()
    let prevpage = page[page.length - 2]
    if (prevpage.route == 'pages/rescue/index/index') { // 如果是道路救援进来，不展示手动选择门店
      console.log('prevpage.route', prevpage.route)
    }
  }
  componentDidHide() { }
  componentDidCatchError() { }
  componentDidNotFound() { }
  // 当前位置信息
  async getLocation(params?) {
    if (process.env.TARO_ENV === 'weapp') {
      const reverseGeocoder: any = await map.reverseGeocoder(params)
      if (reverseGeocoder) {
        const { dispatchLocation } = this.props
        const address = {
          city: reverseGeocoder.ad_info.city,
          address: reverseGeocoder.address,
          location: reverseGeocoder.location,
          title: reverseGeocoder.formatted_addresses.recommend
        }
        dispatchLocation(address)
        this.setState({
          reload: true,
          address,
          loadLocation: true
        })
      } else {
        this.setState({
          reload: true,
          loadLocation: true
        })
      }
    } else {
      const reverseGeocoder: any = await alipayMap.getLocation(true, 3)
      console.log('reverseGeocoder', reverseGeocoder)
      let { city, district, streetNumber } = reverseGeocoder
      if (reverseGeocoder) {
        const { dispatchLocation } = this.props
        const address = {
          city: reverseGeocoder.city,
          address: `${city}${district}${streetNumber.street}${streetNumber.number}`,
          location: reverseGeocoder,
          title: ''
        }
        dispatchLocation(address)
        this.setState({
          reload: true,
          address,
          loadLocation: true
        })
      } else {
        this.setState({
          reload: true,
          loadLocation: true
        })
      }
    }
  }

  // 开启定位
  openSetting() {
    Taro.openSetting().then(res => {
      const status = res.authSetting['scope.userLocation']
      if (status) {
        this.setState({
          reload: false
        })
        this.getLocation()
      }
    })
  }

  // 附近门店数据
  getNearStore(mode?= 'init') {
    const { address } = this.props.location
    const { nearStore } = this.state
    if (mode === 'tab') {
      if (nearStore) {
        return
      }
    }
    console.log('address', address)
    let paramsData = {
      userLongitude: address.location.lng || address.location.longitude,
      userLatitude: address.location.lat || address.location.latitude,
      query: {
        page: this.nearStorePage
      }
    }
    console.log('paramsData--', paramsData)
    // 如果链接携带分销信息 查询门店时需一起发送
    let { goodsDistributionId } = this.$instance.router.params
    if (goodsDistributionId) {
      paramsData.query.goodsDistributionId = goodsDistributionId
    }
    nearStoreApi(paramsData).then(res => {
      const data = res.data.data
      const totalPage = Number(res.header['x-pagination-page-count']) || Number(res.header['X-Pagination-Page-Count'])
      // console.log(this.nearStorePage, totalPage)
      if (this.nearStorePage >= totalPage) {
        this.canAddNearStore = false
      }
      let list = []
      let commonlyUsed = []// 常用门店
      let nearStore = []// 附近门店
      if (nearStore) {
        list = [...nearStore, ...data]
      } else {
        list = [...data]
      }
      list.map((val) => {
        if (val.commonly && val.commonly == 1) {
          commonlyUsed.push(val)
        } else {
          nearStore.push(val)
        }
      })
      this.setState({
        commonlyUsed,
        nearStore,
      })

    })
  }

  // 当前门店数据
  async currStore() {
    const { storeLocation } = this.props.location
    this.setState({
      store: storeLocation
    })
  }

  // 常用门店数据
  getOtfenStore(params?) {
    const { address } = params || this.state
    const { otfenStore } = this.state
    const newParams = {
      userLongitude: address.location.lng,
      userLatitude: address.location.lat,
      query: {
        page: this.otfenStorePage
      }
    }
    // 如果链接携带分销信息 查询门店时需一起发送
    let { goodsDistributionId } = this.$instance.router.params
    if (goodsDistributionId) {
      newParams.query.goodsDistributionId = goodsDistributionId
    }

    oftenStore(newParams).then(res => {
      const data = res.data.data
      const totalPage = Number(res.header['x-pagination-page-count']) || Number(res.header['X-Pagination-Page-Count'])
      if (this.otfenStorePage >= totalPage) {
        this.canAddOtfenStore = false
      }
      if (otfenStore) {
        this.setState({
          otfenStore: [...otfenStore, ...data]
        })
      } else {
        this.setState({
          otfenStore: [...data]
        })
      }
    })
  }

  private addAllStoreStatus = false
  private allStorePage: number = 1
  async addAllStore(e) {
    if (!this.addAllStoreStatus) {
      this.allStorePage++
      this.addAllStoreStatus = true
      await this.getAllStore()
      this.addAllStoreStatus = false
    }
  }
  // 全部门店
  getAllStore(params?) {
    const { address } = params || this.state
    let paramsData = {
      userLongitude: address.location.lng,
      userLatitude: address.location.lat,
      query: {
        page: this.allStorePage
      }
    }
    // 如果链接携带分销信息 查询门店时需一起发送
    let { goodsDistributionId } = this.$instance.router.params
    if (goodsDistributionId) {
      paramsData.query.goodsDistributionId = goodsDistributionId
    }

    allStore(paramsData).then(res => {
      const data = res.data.data
      const { allStoreList } = this.state
      if (allStoreList.length) {
        this.setState({
          allStoreList: [...allStoreList, ...data]
        })
      } else {
        this.setState({
          allStoreList: [...data]
        })
      }
    })
  }
  // 全部门店界面
  allStoreView() {
    const { store, allStoreList } = this.state
    const { method } = this.$instance.router.params
    return (
      <ScrollView lowerThreshold={120} scrollY onScrollToLower={(e) => this.addAllStore(e)} className={classnames('otfen-store', method === 'vendorStore' && 'show')}>
        {
          store && (
            <View className='curr-store'>
              <View className='sub-title'>当前门店</View>
              <View className='store-item'>
                <StoreListView list={store} />
              </View>
            </View>
          )
        }
        {
          allStoreList.length && (
            <View className='otfen-list'>
              <View className='sub-title'>可用门店</View>
              {
                allStoreList.map(list => {
                  return <StoreListView handleEvent={this.changeStore.bind(this)} key={list.id} list={list} />
                })
              }
            </View>
          )
        }
      </ScrollView>
    )
  }

  // 搜索
  searchLocation = debounce((e) => {
    const { value: keyword } = e.detail
    if (keyword) {
      const { address } = this.state
      let paramsData = {
        userLongitude: address.location.lng,
        userLatitude: address.location.lat,
        query: {
					page:1,filter:{or:[{storeNameKeyword:{klike:keyword}},{addressKeyword:{klike:keyword}}]},
				},

      }
      // 如果链接携带分销信息 查询门店时需一起发送
      let { goodsDistributionId } = this.$instance.router.params
      if (goodsDistributionId) {
        paramsData.query.goodsDistributionId = goodsDistributionId
      }
      allStore(paramsData).then(res => {
        const data = res.data.data
        this.setState({
          keyWordStore: data
        })
      })
    } else {
      this.setState({
        keyWordStore: []
      })
    }
  }, 400)

  async changeStore(store?) {
    console.log('store: ', store);
    store['topUrl'] = store['logo']
    const { dispatchStore } = this.props
    await dispatchStore(store)
    this.setState({
      store
    }, () => {
      if (hasPrevRoute()) {
        Taro.navigateBack()
      } else {
        Taro.switchTab({ url: '/pages/tabbar/index/index' })
      }
    })
  }

  private addOtfenStoreStatus = false
  private otfenStorePage = 1
  private canAddOtfenStore: boolean = true
  async addOtfenStore(e) {
    // 暂禁止常用门店滚动加载（考虑到常用门店数据不会多）
    const disableScroll = true
    if (disableScroll) return
    if (!this.canAddOtfenStore) return
    if (!this.addOtfenStoreStatus) {
      this.otfenStorePage++
      this.addOtfenStoreStatus = true
      await this.getOtfenStore()
      this.addOtfenStoreStatus = false
    }
  }

  // 常用门店界面
  otfenStoreView() {
    const { store, otfenStore, tabIndex } = this.state
    return (
      <ScrollView lowerThreshold={120} scrollY onScrollToLower={(e) => this.addOtfenStore(e)} className={classnames('otfen-store', tabIndex === 1 && 'show')}>
        {
          store && (
            <View className='curr-store'>
              <View className='sub-title'>当前门店</View>
              <View className='store-item'>
                <StoreListView handleEvent={this.changeStore.bind(this)} list={store} />
              </View>
            </View>
          )
        }
        {
          otfenStore && otfenStore.length && (
            <View className='otfen-list'>
              <View className='sub-title'>常用门店</View>
              {
                otfenStore.map(list => {
                  return <StoreListView handleEvent={this.changeStore.bind(this)} key={list.id} list={list} />
                })
              }
            </View>
          )
        }
      </ScrollView>
    )
  }
  private canAddNearStore: boolean = true
  private addNearStoreStatus = false
  private nearStorePage = 1
  async addNearStore(e) {

    if (!this.canAddNearStore) return
    if (!this.addNearStoreStatus) {
      this.nearStorePage++
      this.addNearStoreStatus = true
      console.log(this.nearStorePage)
      await this.getNearStore()
      this.addNearStoreStatus = false
    }
  }
  // 附近门店界面
  nearStoreView() {
    const { address, reload, nearStore, commonlyUsed, tabIndex } = this.state
    return (
      <ScrollView lowerThreshold={120} scrollY onScrollToLower={(e) => {
        this.addNearStore(e)
      }} className={classnames('near-store', tabIndex === 2 && 'show')}
      >
        <View className='sub-title'>当前位置</View>
        {
          address ?
            <View className='current-location'>
              <View className='location-info'>
                <View className='name'>{address.title}</View>
                <View className='address'>{address.address}</View>
              </View>
              {/* <AtButton onClick={(e) => Taro.navigateTo({ url: '/pages/store/region/index' })} className='reset-location' size='small' loading={!reload} type='secondary'>
                {!reload ? '' : '重新选择'}
              </AtButton> */}
            </View> :
            <View className='current-location'>
              <View className='location-info'><View className='name'>暂无位置信息</View></View>
              <AtButton className='reset-location' onClick={() => this.openSetting()} size='small' loading={!reload} type='secondary'>
                {!reload ? '' : '开启定位'}
              </AtButton>
            </View>
        }
        {
          nearStore && nearStore.length && (
            <View className='near-list'>
              {
                commonlyUsed && commonlyUsed.length > 0 &&
                <Fragment>
                  <View className='sub-title'>常用门店</View>
                  {
                    commonlyUsed.map(list => {
                      return <StoreListView handleEvent={this.changeStore.bind(this)} key={list.id} list={list} />
                    })
                  }
                </Fragment>
              }
              <View className='sub-title'>附近门店</View>
              {
                nearStore.map(list => {
                  return <StoreListView handleEvent={this.changeStore.bind(this)} key={list.id} list={list} />
                })
              }
            </View>
          )
        }
      </ScrollView>
    )
  }

  // 搜索门店界面
  keywordStoreView() {
    const { keyWordStore } = this.state
    return keyWordStore.length && (
      <View className={classnames('keyword-store-content')}>
        {
          keyWordStore.map(list => {
            return <StoreListView handleEvent={this.changeStore.bind(this)} key={list.id} list={list} />
          })
        }
      </View>
    )
  }

  render() {
    const { tabIndex, loadLocation, address } = this.state
    const { method } = this.$instance.router.params
    return loadLocation && (
      <View className='store-index'>
        {
          address ? (
            <View className={classnames('store-main', method === 'vendorStore' && 'vendor-store')}>
              <View className='store-index-fixed'>
                <View className='import-keywords'><Input placeholder-class='placeholder' onInput={(e) => this.searchLocation(e)} className='ipt' placeholder='输入门店名称、地址或区域'></Input></View>
              </View>
              {method === 'vendorStore' ? this.allStoreView() : this.otfenStoreView()}
              {this.nearStoreView()}
              {this.keywordStoreView()}
            </View>
          ) : <OpenLocation />
        }
      </View>
    )
  }
}
